const msgTemplate = require("../util/messageTemplate");
const birthEight = require("./birthday");

function formmessage(req) {
  // 获取微信传递过来的xml
  let xml = req.xml;
  return new Promise((resolve, reject) => {
    // 判断发送的消息类型
    switch (xml.msgtype[0]) {
      // 接收关注和取关消息
      case "event":
        let msgdata = {
          FromUserName: xml.fromusername[0],
          ToUserName: xml.tousername[0],
          reply: `欢迎关注，请按照如下模板输可获取生辰八字信息\n\n阳历出生日期：2020-5-10\n出生时间(0~23)：5`,
        };
        resolve(msgTemplate.textMessage(msgdata));
        break;
        
      // 接收到文本消息
      case "text":
        // 根据生日获取生辰八字
        birthEight(xml.content[0]).then((birthinfo) => {
          if (birthinfo.error) {
            let msgdata = {
              FromUserName: xml.fromusername[0],
              ToUserName: xml.tousername[0],
              reply: `${birthinfo.message}`,
            };
            resolve(msgTemplate.textMessage(msgdata));
          } else {
            let info = birthinfo.data.result;
            let str = `您的出生信息如下:\n农历出生日期:${info.year}-${
              info.month
            }-${info.day}\n星期:${info.ncWeek}\n属性:${info.Animal}\n星座:${
              info.astro
            }\n八字:${info.eightAll.eight.join("、")}\n属${
              info.eightAll.shu
            }\n五行:${info.fiveAll.five.join("、")}\n缺${info.fiveAll.lose}`;
            let msgdata = {
              FromUserName: xml.fromusername[0],
              ToUserName: xml.tousername[0],
              reply: `${str}`,
            };
            resolve(msgTemplate.textMessage(msgdata));
          }
        });
        break;

      default:
        // 发送无用的消息是响应一个空字符串
        resolve("");
        break;
    }
  });
}

module.exports = formmessage;
